/*
 * Copyright (c) 2015 www.jd.com All rights reserved.
 * 本软件源代码版权归京东智能集团所有,未经许可不得任意复制与传播.
 */
package com.test;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * <b>描述：</b> <br/>
 *
 * @author <b>作者：</b> wutao91@jd.com<br/>
 * @date <b>时间：</b> 2021/7/16 15:02<br/>
 * <b>Copyright (c)</b> 2015-2021京东智能-版权所有<br/>
 */
public class ServerHandler extends ChannelInboundHandlerAdapter {
    private static final ConcurrentMap<String, String> userMap = new ConcurrentHashMap<>();
    private static final ConcurrentMap<String, Channel> channelMap = new ConcurrentHashMap<>();
    
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object o) throws Exception {
        ByteBuf buf = (ByteBuf) o;
        byte[] input = new byte[buf.readableBytes()];
        buf.readBytes(input);
        String data = new String(input);
        JSONObject dataObj = JSONUtil.parseObj(data);
        int type = dataObj.getInt("type");
        Channel fromChannel = ctx.channel();
        if (type == 1) {
            //注册
            String channelId = fromChannel.id().asLongText();
            if (!userMap.containsKey(channelId)) {
                String user = dataObj.getStr("name");
                userMap.put(channelId, user);
                channelMap.put(user, fromChannel);
                System.out.println(user + "接入");
                byte[] response = ("注册成功").getBytes();
                ByteBuf responseBuf = Unpooled.buffer(response.length);
                responseBuf.writeBytes(response);
                fromChannel.writeAndFlush(responseBuf);
            }
            return;
        }
        String from = dataObj.getStr("from");
        String to = dataObj.getStr("to");
        if (from.equals(to)) {
            return;
        }
        String msg = dataObj.getStr("msg");
        System.out.println(from + "-->" + to + "：" + msg);
        Channel toChannel = channelMap.get(to);
        byte[] fromBytes;
        if (toChannel == null) {
            fromBytes = ("用户 " + to + " 不在线, 消息发送失败").getBytes();
        } else {
            byte[] toBytes = (from + "：" + msg).getBytes();
            ByteBuf toBuf = Unpooled.buffer(toBytes.length);
            toBuf.writeBytes(toBytes);
            toChannel.writeAndFlush(toBuf);
            fromBytes = ("我-->" + to + "：" + msg).getBytes();
        }
        ByteBuf fromBuf = Unpooled.buffer(fromBytes.length);
        fromBuf.writeBytes(fromBytes);
        fromChannel.writeAndFlush(fromBuf);
    }
    
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        String channelId = ctx.channel().id().asLongText();
        String user = userMap.remove(channelId);
        channelMap.remove(user);
        System.out.println(user + "退出");
    }
}
